package com.yfbao.horizon.sacn;


import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.net.JarURLConnection;
import java.net.URL;
import java.net.URLDecoder;
import java.util.*;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;

public class ClassHelper {
    /**
     * 定义类集合，用于存放所加载的类
     */
    private static final Set<Class<?>> CLASS_SET;

    static {
        //静态加载类
        String basePackage = "C:\\Users\\byf78\\Desktop\\日志分析\\接口流量测算\\ctp-user-assemble.jar";
//        String basePackage  ="com.yfbao.horizon.model";
//        CLASS_SET = ClassUtil.getClassSet(basePackage);

        CLASS_SET = getClzFromPkg(basePackage);

    }

    /**
     * 获取应用包下的所有类
     */
    public static Set<Class<?>> getClassSet() {
        return CLASS_SET;
    }

    /**
     * 获取应用包名下所有Service类
     */
    public static Set<Class<?>> getServiceClassSet() {
        Set<Class<?>> classSet = new HashSet<Class<?>>();
        for (Class<?> cls : CLASS_SET) {
            if (cls.getAnnotation(Service.class) !=null) {
                classSet.add(cls);
            }
        }
        return classSet;
    }

//    /**
//     * 获取应用包名下所有Service类
//     */
//    public static Set<Class<?>> getAppServiceClassSet() {
//        Set<Class<?>> classSet = new HashSet<Class<?>>();
//        for (Class<?> cls : CLASS_SET) {
//            if (cls.getAnnotation(AppSer.class) !=null) {
//                classSet.add(cls);
//            }
//        }
//        return classSet;
//    }

    /**
     * 获取应用包名下所有Controller类
     */
    public static Set<Class<?>> getControllerClassSet() {
        Set<Class<?>> classSet = new HashSet<Class<?>>();
        for (Class<?> cls : CLASS_SET) {
            if (cls.getAnnotation(RestController.class) != null) {
                classSet.add(cls);
            }
        }
        return classSet;
    }
    /**
     * 获取应用包名下所有Bean类(包括Service，Controller)
     */
    public static Set<Class<?>> getBeanClassSet() {
        Set<Class<?>> beanClassSet = new HashSet<Class<?>>();
        beanClassSet.addAll(getServiceClassSet());
        beanClassSet.addAll(getControllerClassSet());
        return beanClassSet;
    }


    /**
     * 获取类中有指定注解的方法
     * @param annotationClass
     * @param <A>
     * @return
     */
    public static <A extends Annotation> Map<String, List<Method>> getTargetMetods(Class<A> annotationClass ){
        Map<String, List<Method>> map = new HashMap<>();
        for (Class<?> cls : CLASS_SET) {
            Method[] methods = cls.getMethods();
            for (Method method : methods) {
//                Annotation[] allMAnnos = method.getAnnotations();
//                Annotation[] deMAnnos = method.getDeclaredAnnotations();
//                Annotation subMAnno = method.getAnnotation(SubAnnotation.class);
//                Annotation parentMAnno = method.getAnnotation(ParentAnnotation.class);
//                printAnnotation("allMAnnos",allMAnnos);
//                printAnnotation("deMAnnos",deMAnnos);
//                printAnnotation("subMAnno",subMAnno);
//                printAnnotation("parentMAnno",parentMAnno);
                if(method.getAnnotation(annotationClass)!=null){
                    List<Method> methodList = map.get(cls.getName());
                    if(methodList ==null){
                        methodList = new ArrayList<>();
                    }
                    methodList.add(method);
                    map.put(cls.getName(),methodList);
                }
            }
        }
        return map;
    }



    /**
     * 从包package中获取所有的Class
     *
     * @param pkg
     * @return
     */
    public static Set<Class<?>> getClzFromPkg(String pkg) {
        //第一个class类的集合
        Set<Class<?>> classes = new LinkedHashSet<>();
        // 获取包的名字 并进行替换
        String pkgDirName = pkg.replace('.', '/');
        try {
            Enumeration<URL> urls = ClassHelper.class.getClassLoader().getResources(pkgDirName);
            while (urls.hasMoreElements()) {
                URL url = urls.nextElement();
                // 得到协议的名称
                String protocol = url.getProtocol();
                // 如果是以文件的形式保存在服务器上
                if ("file".equals(protocol)) {
                    // 获取包的物理路径
                    String filePath = URLDecoder.decode(url.getFile(), "UTF-8");
                    // 以文件的方式扫描整个包下的文件 并添加到集合中
                    findClassesByFile(pkg, filePath, classes);
                } else if ("jar".equals(protocol)) {
                    // 如果是jar包文件
                    // 获取jar
                    JarFile jar = ((JarURLConnection) url.openConnection()).getJarFile();
                    //扫描jar包文件 并添加到集合中
                    findClassesByJar(pkg, jar, classes);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        return classes;
    }

    private static void findClassesByFile(String pkgName, String pkgPath, Set<Class<?>> classes) {
        // 获取此包的目录 建立一个File
        File dir = new File(pkgPath);
        // 如果不存在或者 也不是目录就直接返回
        if (!dir.exists() || !dir.isDirectory()) {
            return;
        }
        // 如果存在 就获取包下的所有文件 包括目录
//        File[] dirfiles = dir.listFiles(new FileFilter() {
//            // 自定义过滤规则 如果可以循环(包含子目录) 或则是以.class结尾的文件(编译好的java类文件)
//            public boolean accept(File file) {
//                return file.isDirectory()|| file.getName().endsWith(".class");
//            }
//        });
        File[] dirfiles = dir.listFiles(pathname -> pathname.isDirectory() || pathname.getName().endsWith("class"));

        if (dirfiles == null || dirfiles.length == 0) {
            return;
        }

        String className;
        Class clz;
        // 循环所有文件
        for (File f : dirfiles) {
            // 如果是目录 则继续扫描
            if (f.isDirectory()) {
                findClassesByFile(pkgName + "." + f.getName(),pkgPath + "/" + f.getName(),classes);
                continue;
            }
            // 如果是java类文件 去掉后面的.class 只留下类名
            className = f.getName();
            className = className.substring(0, className.length() - 6);

            //加载类
            clz = loadClass(pkgName + "." + className);
            // 添加到集合中去
            if (clz != null) {
                classes.add(clz);
            }
        }
    }

    private static void findClassesByJar(String pkgName, JarFile jar, Set<Class<?>> classes) {
        String pkgDir = pkgName.replace(".", "/");
        // 从此jar包 得到一个枚举类
        Enumeration<JarEntry> entry = jar.entries();

        JarEntry jarEntry;
        String name, className;
        Class<?> claze;
        // 同样的进行循环迭代
        while (entry.hasMoreElements()) {
            // 获取jar里的一个实体 可以是目录 和一些jar包里的其他文件 如META-INF等文
            jarEntry = entry.nextElement();

            name = jarEntry.getName();
            // 如果是以/开头的
            if (name.charAt(0) == '/') {
                // 获取后面的字符串
                name = name.substring(1);
            }

            if (jarEntry.isDirectory() || !name.startsWith(pkgDir) || !name.endsWith(".class")) {
                continue;
            }
            //如果是一个.class文件 而且不是目录
            // 去掉后面的".class" 获取真正的类名
            className = name.substring(0, name.length() - 6);
            //加载类
            claze = loadClass(className.replace("/", "."));
            // 添加到集合中去
            if (claze != null) {
                classes.add(claze);
            }
        }
    }

    /**
     *    加载类
     * @param fullClzName 类全名
     * @return
     */
    private static Class<?> loadClass(String fullClzName) {
        try {
            return Thread.currentThread().getContextClassLoader().loadClass(fullClzName);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        return null;
    }


    public static void checkJarClass(String file) throws IOException {
        JarFile jarFile = new JarFile(file);     //ctp-user-biz-2.7.0-TEST-SNAPSHOT.jar");
        Enumeration enu = jarFile.entries();
        while (enu.hasMoreElements()) {
            JarEntry jarEntry = (JarEntry) enu.nextElement();
            String name = jarEntry.getName();
            if (name.endsWith(".class")) {
                System.out.println("name=" + name);
                continue;
            }
//            System.out.println("unknow:"+name);
        }
    }

    public static Set<String> checkAndGetJarClass(String file) throws IOException {
        Set<String> set = new HashSet<>();
        JarFile jarFile = new JarFile(file);     //ctp-user-biz-2.7.0-TEST-SNAPSHOT.jar");
        Enumeration enu = jarFile.entries();
        while (enu.hasMoreElements()) {
            JarEntry jarEntry = (JarEntry) enu.nextElement();
            String name = jarEntry.getName();
            if (name.endsWith(".class")) {
                String className = name.substring(0, name.lastIndexOf("."))
                        .replaceAll("/", ".");
//                System.out.println("name=" + className);
                set.add(className);
                continue;
            }
//            System.out.println("unknow:"+


        }
        return set;
    }



    public static Set<String> scanAndGetTargetClassSet(String dir,String targetPrefix) throws IOException {

        JarLoaderUtil.loadJarPath(dir);
        ArrayList<File> list = new ArrayList<>();
        JarLoaderUtil.loopFiles(new File(dir),list);
        Set<String> tarJar = new HashSet<>();
        System.out.println("jar size:"+list.size());
        for (File file1 : list) {
            if(file1.getName().contains(targetPrefix)){
                tarJar.add(file1.getAbsolutePath());
            }
        }
        Set<String> tagClassSet = new HashSet<>();
        for (String jar : tarJar) {
            System.out.println("开始加载jar包："+jar);
            Set<String> set = checkAndGetJarClass(jar);
            tagClassSet.addAll(set);
        }
        System.out.println("jar class size:"+tagClassSet.size());
        return tagClassSet;
    }

    public static <A extends Annotation> Set<Class<?>> getTargetAnnotaitonClazzFromSet(Set<String> set,Class<A> annotationClass){
        Set<Class<?>> clazzSet = new HashSet<>();
        for (String jar : set) {
            Class<?> aClass = JarLoaderUtil.getClass(jar);
            if(aClass ==null){
                System.out.println("查找类异常未找到："+jar);
                continue;
            }
            if (aClass.getAnnotation(annotationClass) != null) {
                clazzSet.add(aClass);
                continue;
            }
            Annotation[] annotations = aClass.getAnnotations();
            for(int i =0;i<annotations.length;i++){
                Annotation annotation = annotations[i];
                if( annotation.annotationType().getSimpleName().equals(annotationClass.getSimpleName())){
                    clazzSet.add(aClass);
                    break;
                }
            }
        }
//        List<Class<?>> controllerClasses = new ArrayList<>();
//        Reflections reflections = new Reflections("com.seeyon.ctp.manager.controller");
//        Set<Class<?>> annotatedClasses = reflections.getTypesAnnotatedWith(Controller.class);
//        controllerClasses.addAll(annotatedClasses);
//
//        Set<Class<?>> annotatedRestClasses = reflections.getTypesAnnotatedWith(RestController.class);
//        controllerClasses.addAll(annotatedRestClasses);
        return clazzSet;
    }

    public static <A extends Annotation> boolean checkMetodAnnotations(Method method,Class<A> annotationClass){
        Annotation[] annotations = method.getAnnotations();
        for (Annotation annotation : annotations) {
            if( annotation.annotationType().getSimpleName().equals(annotationClass.getSimpleName())){
                return true;
            }
        }
        return false;
    }


    public static <A extends Annotation> Annotation getMetodAnnotations(Method method,Class<A> annotationClass){
        Annotation[] annotations = method.getAnnotations();
        for (Annotation annotation : annotations) {
            if( annotation.annotationType().getSimpleName().equals(annotationClass.getSimpleName())){
                return annotation;
            }
        }
        return null;
    }

    public static void main(String args[]) {
        try {
//            String file ="C:\\Users\\byf78\\Desktop\\日志分析\\接口流量测算\\ctp-user-assemble.jar";
            String file ="C:\\Users\\byf78\\Desktop\\日志分析\\接口流量测算\\jar";
            String prefix = "ctp-user";
            Set<String> set = scanAndGetTargetClassSet(file, prefix);
            Set<Class<?>> restAnnotaitonClazzFromSet = getTargetAnnotaitonClazzFromSet(set, RestController.class);
            System.out.println("RestController class size:"+restAnnotaitonClazzFromSet.size());

            Set<Class<?>> dubboAnnotaitonClazzFromSet = getTargetAnnotaitonClazzFromSet(set, RestController.class);
            System.out.println("Dubbo class size:"+dubboAnnotaitonClazzFromSet.size());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}


